package org.fing.edu.uy.esbadp.property.monitor;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.fing.edu.uy.esbadp.core.entity.DMRegisteredService;
import org.fing.edu.uy.esbadp.core.interfaces.IAdpProperties;
import org.fing.edu.uy.esbadp.logger.LoggerADP;


public class InvocationsQuantityPerUnitTimeProperty implements IAdpProperties {

	private static final java.util.logging.Logger logger = LoggerADP.getLogger(InvocationsQuantityPerUnitTimeProperty.class.getSimpleName());
	
	private Map<Long, Map<String, Object>> cachedMechanisms;
	
	public InvocationsQuantityPerUnitTimeProperty(){
		cachedMechanisms = new HashMap<Long, Map<String,Object>>();
	}
	
	@Override
	public Object getPropertyValue(Map<String, Object> mechanisms,  DMRegisteredService service) {		
		try{
			int invocationsQuantityPerUnitTime = 0;
			int failCount = (Integer) mechanisms.get("failCount");
			int successCount = (Integer) mechanisms.get("successCount");
			
			int lastFailCount = 0;
			int lastSuccessCount = 0;
			
			Map<String, Object> oldMechanism = null;
			
			if(cachedMechanisms.containsKey(service.getServiceID())){
				oldMechanism = cachedMechanisms.get(service.getServiceID());
				lastFailCount = (Integer) oldMechanism.get("failCount");
				lastSuccessCount = (Integer) oldMechanism.get("successCount");
			}
			
			int intervalFailCount = failCount - lastFailCount;
			int intervalSuccessCount = successCount - lastSuccessCount;
			invocationsQuantityPerUnitTime = intervalFailCount + intervalSuccessCount;
			
			if(oldMechanism == null){
				oldMechanism = new HashMap<String, Object>();
				cachedMechanisms.put(service.getServiceID(), oldMechanism);
			}	
			
			oldMechanism.put("failCount", failCount);
			oldMechanism.put("successCount", successCount);
			
			return invocationsQuantityPerUnitTime;		
			
		}catch(Exception ex){
			logger.log(Level.SEVERE, "Exception in InvocationsQuantityPerUnitTimeProperty...\n StackTarce => [ {0} ]", ExceptionUtils.getStackTrace(ex));	
			return null; 
		}	
	}
}
